package com.right.near.common.aspect;

import com.right.near.business.model.dto.UserDetailDTO;
import com.right.near.common.service.IOperatingUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Objects;

/**
 * 操作用户自动填充
 *
 * @author: star
 * @date: 2022/7/18
 */
@Slf4j
@Aspect
@Component
public class OperatingUserAspect {

//    @Autowired
//    private CurrentUserUtil currentUserUtil;

    /**
     * pointcut
     */
    @Pointcut("@annotation(com.right.near.common.annotation.OperatingUser)")
    public void aspect() {
    }

    /***
     * interception
     *
     * @param joinPoint join point
     */
    @Around(value = "aspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (Objects.nonNull(joinPoint)) {
            processParameters(joinPoint.getArgs());
            return joinPoint.proceed();
        } else {
            return null;
        }
    }

    /**
     * processing request content
     */
    private void processParameters(Object[] args) {
        try {
//            UserDetail user = currentUserUtil.getUser();
            UserDetailDTO user = new UserDetailDTO();
            user.setId("1");
            user.setUserName("测试");
            user.setRoles(Arrays.asList("测试"));
            if (Objects.isNull(user)) {
                log.warn("当前未登录无法注入操作用户");
            } else {
                if (null != args) {
                    int length = args.length;
                    for (int i = 0; i < length; i++) {
                        Object o = args[i];
                        if (o instanceof MultipartFile) {
                            continue;
                        }
                        if (o instanceof IOperatingUser) {
                            IOperatingUser operatingUser = (IOperatingUser) o;
                            operatingUser.setOperationUserId(user.getId());
                            operatingUser.setOperationUserName(user.getUsername());
                            operatingUser.setOperationUserRole(user.getRoles());
                        }
                    }
                } else {
                    log.warn("参数为空未注入操作用户");
                }
            }
        } catch (Exception e) {
            log.error("handling returned data exception：{}", e.getMessage());
        }
    }

}
